<template>
  <view class="user_login" :style="'padding-top: ' + menuButton.bottom + 'px;height: ' + screenHeight + 'px;'">
    <Head title="用户登陆" :transparent="false">
      <!-- <text slot="action">搜索</text> -->
    </Head>
    <view class="login_box">
      <view class="tab_box">
        <!-- #ifdef MP-TOUTIAO -->
        <text class="item" :class="currentTabIndex === 0 ? 'active_tab' : ''" @click="currentTabIndex = 0">抖音一键登陆</text>
        <!-- #endif -->
        <!-- #ifdef MP-WEIXIN -->
        <text class="item" :class="currentTabIndex === 0 ? 'active_tab' : ''" @click="currentTabIndex = 0">微信一键登陆</text>
        <!-- #endif -->
        <!-- #ifdef MP-QQ -->
        <text class="item" :class="currentTabIndex === 0 ? 'active_tab' : ''" @click="currentTabIndex = 0">QQ一键登陆</text>
        <!-- #endif -->
        <text class="item" :class="currentTabIndex === 1 ? 'active_tab' : ''" @click="currentTabIndex = 1">手机验证登陆</text>
      </view>
      <swiper :current="currentTabIndex" class="swiper_box" @change="touchSwiper">
        <!-- #ifdef MP-TOUTIAO -->
        <swiper-item>
          <!-- 抖音一键登陆 -->
          <view class="login_form" v-show="currentTabIndex === 0">
            <button class="login_btn wechat_login" @click="ttLogin">抖音一键登陆</button>
          </view>
        </swiper-item>
        <!-- #endif -->

        <!-- #ifdef MP-WEIXIN -->
        <swiper-item>
          <!-- 微信一键登陆 -->
          <view class="login_form" v-show="currentTabIndex === 0">
            <button v-if="canIUseGetUserProfile" class="login_btn wechat_login" @click="getUserProfile"><text class="login">一键登陆/注册</text></button>
            <button v-if="!canIUseGetUserProfile" class="login_btn wechat_login" open-type="getUserInfo" @getuserinfo="wxLogin">
              <text class="login">一键登陆/注册</text>
            </button>
          </view>
        </swiper-item>
        <!-- #endif -->
        
        <!-- #ifdef MP-QQ -->
        <swiper-item>
          <!-- QQ一键登陆 -->
          <view class="login_form" v-show="currentTabIndex === 0">
            <button class="login_btn wechat_login" open-type="getUserInfo" @getuserinfo="qqLogin">QQ一键登陆</button>
          </view>
        </swiper-item>
        <!-- #endif -->

        <swiper-item>
          <!-- 短信验证码登陆 -->
          <view class="login_form">
            <view class="form_item">
              <text class="label">手机号：</text>
              <view class="text">
                <input type="number" :maxlength="11" class="input" v-model="loginForm.mobile" placeholder="未注册手机验证后自动登陆" />
              </view>
            </view>
            <view class="form_item">
              <text class="label">验证码：</text>
              <view class="text">
                <input type="number" :maxlength="6" class="input" v-model="loginForm.verify" />
                <text class="verify_code" @click="getVerify">{{countDown ? countDown + 'S' : '获取验证码'}}</text>
              </view>
            </view>
            <button class="login_btn" @click="verifyLogin">登陆</button>
          </view>
        </swiper-item>
      </swiper>
    </view>
  </view>
</template>

<script>
  import Head from '@/pages/pagecomponents/head'
  export default {
    components: {
      Head,
    },
    data() {
      return {
        menuButton: this.menuButton,
        appNameCNY: this.appNameCNY,
        canIUseGetUserProfile: false, // 判断使用新/旧用户信息接口
        currentTabIndex: 0,
        countDown: 0, // 60S倒计时
        loginForm: {
          mobile: '',
          verify: '',
        },
        verifyInterval: null, // 60S倒计时计时器
        screenHeight: uni.getSystemInfoSync().screenHeight, // 屏幕高度
      }
    },
    onLoad() {
      if (wx.getUserProfile) {
        // 使用新接口登录
        this.canIUseGetUserProfile = true;
      }
    },
    methods: {
      touchSwiper(e) {
        // 手动滑动切换轮播
        this.currentTabIndex = e.detail.current
      },
      verifyLogin() {
        let loginForm = this.loginForm
        let hasNull = false;
        Object.keys(loginForm).some(item => {
          if (!loginForm[item] || loginForm[item] === '') {
            hasNull = true;
            return true;
          }
        })
        if (hasNull) {
          uni.showToast({
            icon: 'none',
            title: '对不起，请将表单填写完整后提交'
          });
          return;
        } else if (!/^1[3456789]\d{9}$/.test(loginForm.mobile)) {
          uni.showToast({
            icon: 'none',
            title: '对不起，请输入正确手机号'
          });
          return;
        } else if (!/^[0-9]{6}$/.test(loginForm.verify)) {
          uni.showToast({
            icon: 'none',
            title: '对不起，请输入6位验证码'
          });
          return;
        }
        // 短信验证码登陆
        this.$api.user.verifyLogin({
          mobile: this.loginForm.mobile,
          verify: this.loginForm.verify,
        }).then(res => {
          // 调用刷新用户信息方法
          this.$store.commit('refreshUserInfo')
          uni.showToast({
            title: res.data,
          });
          uni.navigateBack({
              delta: 1
          });
        })
      },
      getVerify() {
        let loginForm = this.loginForm
        if (loginForm.mobile === '') {
          uni.showToast({
            icon: 'none',
            title: '对不起，请输入手机号'
          });
          return;
        } else if (!/^1[3456789]\d{9}$/.test(loginForm.mobile)) {
          uni.showToast({
            icon: 'none',
            title: '对不起，请输入正确手机号'
          });
          return;
        }
        // 获取短信验证码
        if (this.countDown <= 0) {
          this.$api.user.verifySend({
            mobile: this.loginForm.mobile,
          }).then(res => {
            this.countDown = 60
            this.verifyInterval = setInterval(() => {
              if (this.countDown <= 0) {
                clearInterval(this.verifyInterval);
              } else {
                this.countDown = this.countDown - 1
              }
            }, 1000)
          })
        }
      },
      ttLogin() {
        // 头条一键登陆
        uni.login({
          // provider: 'weixin',
          success: res => {
            console.log(`login调用成功${res.code} ${res.anonymousCode}`);
            let code = res.code; //登录凭证
            let anonymousCode = res.anonymousCode; //登录凭证
            if (code) {
              uni.authorize({
                scope: 'scope.userInfo',
                success: res => {
                  uni.getUserInfo({
                    success: userInfo => {
                      this.$api.user.ttLogin({ // 登陆接口
                        ...userInfo,
                        code: code,
                        anonymousCode: anonymousCode,
                      }).then(res => {
                        // 调用刷新用户信息方法
                        this.$store.commit('refreshUserInfo')
                        uni.showToast({
                          title: res.data,
                        });
                        uni.navigateBack({
                            delta: 1
                        });
                      })
                    },
                    fail: err => {
                      uni.showToast({
                        icon: 'none',
                        title: '获取授权失败',
                      });
                    }
                  })
                },
                fail: res => {
                  uni.openSetting({
                    success: res => {},
                    fail: err => {
                      uni.showToast({
                        icon: 'none',
                        title: '获取授权失败',
                      });
                    }
                  })
                }
              })
            }
          }
        });
      },
      getUserProfile() {
        // 新版获取用户信息
        wx.getUserProfile({
          desc: '用于一键注册本平台账号', // 声明获取用户个人信息后的用途，后续会展示在弹窗中
          success: userInfo => {
            // console.log(userInfo);
            wx.login({
              // provider: 'weixin',
              success: res1 => {
                if (res1.code) {
                  this.$api.user.wechatLogin({ code: res1.code, ...userInfo }).then(res2 => {
                    // 调用刷新用户信息方法
                    this.$store.commit('refreshUserInfo')
                    uni.showToast({
                      title: res2.data,
                    });
                    uni.navigateBack({
                        delta: 1
                    });
                  });
                }
              }
            });
          },
          fail: err => {
            uni.showToast({
              icon: 'none',
              title: err
            });
          }
        });
      },
      wxLogin(e) {
        if (e.mp.detail.rawData) {
          // 用户成功授权
          uni.login({
            // provider: 'weixin',
            success: res => {
              let code = res.code; //登录凭证
              if (code) {
                uni.getUserInfo({
                  success: userInfo => {
                    this.$api.user.wechatLogin({ // 登陆接口
                      ...userInfo,
                      code: code,
                    }).then(res => {
                      // 调用刷新用户信息方法
                      this.$store.commit('refreshUserInfo')
                      uni.showToast({
                        title: res.data,
                      });
                      uni.navigateBack({
                          delta: 1
                      });
                    })
                  },
                  fail: err => {
                    uni.showToast({
                      icon: 'none',
                      title: err,
                    });
                  }
                })
              }
            }
          });
        } else {
          // 用户拒绝授权
          uni.showToast({
            icon: 'none',
            title: '您已拒绝授权，部分功能可能受阻'
          });
        }
      },
      qqLogin(e){
        uni.login({
          // provider: 'qq',
          success: res => {
            let code = res.code; //登录凭证
            if (code) {
              uni.getUserInfo({
                success: userInfo => {
                  this.$api.user.qqLogin({ // 登陆接口
                    ...userInfo,
                    code: code,
                  }).then(res => {
                    // 调用刷新用户信息方法
                    this.$store.commit('refreshUserInfo')
                    uni.showToast({
                      title: res.data,
                    });
                    uni.navigateBack({
                        delta: 1
                    });
                  })
                },
                fail: err => {
                  uni.showToast({
                    icon: 'none',
                    title: '您已拒绝授权，部分功能可能受阻',
                  });
                }
              })
            }
          }
        });
      },
    }
  }
</script>

<style scoped lang="scss">
  .user_login {
    display: flex;
    justify-content: center; // 水平居中
    align-items: center; // 垂直居中
    .login_box {
      padding: 50upx 40upx 0;
      margin: 0 auto;
      width: 700upx;
      background: #efefef;
      border-radius: 20upx;
      .tab_box {
        border-bottom: 1px solid #b1b6bd;
        .item {
          width: 50%;
          display: inline-block;
          padding: 0 0 40upx;
          font-size: 40upx;
          text-align: center;
        }
        .active_tab {
          border-bottom: 2px solid #2f5085;
        }
      }
      .swiper_box {
        height: 400upx;
        .login_form {
          margin-top: 50upx;
          .login_btn {
            margin-top: 20upx;
            padding: 0 60upx;
            font-size: 30upx;
            border-radius: 10upx;
            height: 80upx;
            line-height: 80upx;
            background-color: #294d7d;
            color: #ffffff;
          }
          .wechat_login {
            margin-top: 140upx;
          }
          .form_item {
            margin-bottom: 40upx;
            font-size: 30upx;
            line-height: 70upx;
            .label {
              display: inline-block;
              width: 150upx;
              height: 70upx;
              vertical-align: middle;
            }
            .text {
              display: inline-block;
              position: relative;
              width: 470upx;
              height: 70upx;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              vertical-align: middle;
              .input {
                height: 70upx;
                line-height: 70upx;
                border-bottom: 1px solid #C8C8C8;
              }
              .verify_code {
                z-index: 1000;
                position: absolute;
                display: inline-block;
                padding: 5upx 20upx;
                right: 0;
                top: 0;
                border-radius: 40upx;
                font-size: 30upx;
                line-height: 40upx;
                color: #ffffff;
                background: #b1b6bd;
              }
            }
          }
        }
      }
    }
  }
</style>
